package com.hzw.net.page.status

import android.content.Context
import android.graphics.Color
import android.view.View
import android.view.ViewGroup
import com.hzw.net.R

class PageStatusManager private constructor(builder: Builder) : IPageStatusEvent {

    val titleView = builder.titleView

    val contentView: View = builder.contentView

    val loadingPageStatus: ILoadingStatus = builder.loadingPageStatus

    val emptyPageStatus: IAbnormalStatus = builder.emptyPageStatus

    val errorPageStatus: IAbnormalStatus = builder.errorPageStatus

    val rootLayout: PageStatusLayout = PageStatusLayout(builder.context).also {
        it.layoutParams = if (builder.isWrapContent) {
            ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
        } else {
            ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
        }
        it.setBackgroundColor(Color.WHITE)
        it.setBackgroundResource(builder.background)
        it.setPageStatusManager(this)
    }

    override fun showLoading(isHideOther: Boolean) {
        rootLayout.showLoading(isHideOther)
    }

    override fun hideLoading() {
        rootLayout.hideLoading()
    }

    override fun isLoading(): Boolean {
        return rootLayout.isLoading()
    }

    override fun showContent() {
        rootLayout.showContent()
    }

    override fun showEmpty(imageResId: Int, text: String, retryText: String?) {
        rootLayout.showEmpty(imageResId, text, retryText)
    }

    override fun showError(imageResId: Int, text: String, retryText: String?) {
        rootLayout.showError(imageResId, text, retryText)
    }

    class Builder(val context: Context) {

        internal var isWrapContent = false

        internal var titleView: View? = null

        internal lateinit var contentView: View

        internal var background: Int = R.color.white

        internal lateinit var loadingPageStatus: ILoadingStatus

        internal lateinit var emptyPageStatus: IAbnormalStatus

        internal lateinit var errorPageStatus: IAbnormalStatus

        fun isWrapContent(isWrapContent: Boolean = false) =
            apply { this.isWrapContent = isWrapContent }

        fun background(bg: Int) = apply { this.background = bg }

        fun title(titleView: View?) = apply { this.titleView = titleView }

        fun content(contentView: View) = apply { this.contentView = contentView }

        fun empty(abnormalStatus: IAbnormalStatus) = apply { emptyPageStatus = abnormalStatus }

        fun error(abnormalStatus: IAbnormalStatus) = apply { errorPageStatus = abnormalStatus }

        fun loading(loadingStatus: ILoadingStatus) = apply { loadingPageStatus = loadingStatus }

        fun build(): PageStatusManager = PageStatusManager(this)
    }
}